<template>
  <div class="page-main" v-title data-title="标准样管理">
    <a-spin :spinning="spinning" >
      <div class="floatNavLeft">
        <a-button  :loading="btnLoading" type="primary" v-show="isEdit && !!stdSampleInfo.id && !currentTaskEdit"  @click="onSubmitForm">提交审批</a-button>
        <a-button  :loading="btnLoading" @click="delForm"   type="danger" v-show="isEdit && !!stdSampleInfo.id ">删除标准</a-button>
          
      </div>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">标准样管理</span>
        <div class="btn-line">
          <a-button class="hte-btn" @click="save()" :loading="btnLoading"  v-show="isEdit">保存</a-button>
          <a-button class="hte-btn add-btn" :loading="btnLoading" type="primary" v-show="isEdit && !!stdSampleInfo.id && !currentTaskEdit"  @click="onSubmitForm">提交审批</a-button>
          <a-button class="hte-btn del-btn" :loading="btnLoading"   type="danger" @click="delForm" v-show="isEdit && !!stdSampleInfo.id ">删除标准</a-button>
        </div>
       
      </div>
      <div class="fixed-menu std-menu" style="top:99px;"  v-show="stdSampleInfo.dataVersion == stdSampleInfo.currentDataVersion">
    
        <div  class="functionMould" style="background-color: #ffffff" @click="handAction('his')">
          <a-icon type="history" class="menu-icon" />
          <span> 历史版本</span>
        </div>
      </div>
      <div class="content mt20">
        <a-form-model ref="ruleForm" :model="stdSampleInfo" :rules="rules" :label-col="{ span: 5 }">
          <section>
            <div class="section-header">基本信息
            </div>   
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="标准样类型" prop="stdMold">
                  <a-radio-group name="stdTypeGroup" v-model="stdSampleInfo.stdMold" :disabled="!isEdit || !!stdSampleInfo.id" @change="stdMoldChange">
                    <a-radio :value="item.code" v-for="item in dict.orderList0" :key="item.code">
                      {{ item.name }}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                  <a-form-model-item label="状态"   >
                      <span>{{stdSampleInfo.status | stdSampleStatusFilter}}</span>
                  </a-form-model-item>                
                </a-col> 
            </a-row>        
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="编制部门">
                  <a-input v-model="stdSampleInfo.editDep" disabled placeholder="系统自动生成"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item  label="编制人">
                  <a-input disabled placeholder="系统自动生成" v-model="stdSampleInfo.createUser" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item  label="发布时间">
                  <a-input v-model="stdSampleInfo.pushTime" disabled placeholder="系统自动生成"/>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="物料名称" prop="maraMaktx"> 
                  <!-- <a-input v-model="stdSampleInfo.maraMaktx" placeholder="请选择物料名称" :disabled="!isEdit" read-only @click="selectOpen('mara','选择物料')"/> -->
                  <MaraSelect ref="mara" v-model="stdSampleInfo.maraMaktx" @ok="(res)=>selectOk(res,'mara')" :clear="false" :disabled="!isEdit|| !!stdSampleInfo.id"></MaraSelect>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="物料编号" prop="maraMatnr">
                  <a-input v-model="stdSampleInfo.maraMatnr" :disabled="!isEdit" placeholder="选择物料名称自动带出" read-only/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="目录" prop="stdType">
                  <a-tree-select 
                    :disabled="!isEdit || !!stdSampleInfo.id"
                    v-model="stdSampleInfo.stdType"
                    :tree-data="treeData"
                    placeholder="请选择目录分类"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    allow-clear
                    show-search
                    tree-node-filter-prop="title"
                    :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
                  >
              </a-tree-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :span="8">
                <a-form-model-item   label="原标准样编号" prop="parentStdNo">
                  <a-input  :disabled="!isEdit || (!!stdSampleInfo.id&& stdSampleInfo.stdMold=='2')" v-model="stdSampleInfo.parentStdNo" placeholder="请选择原标准样编号" @click="selectOpen('parentStdNo','选择原标准样编号')" read-only>
                    <a-icon  class="anticon anticon-close-circle ant-input-clear-icon" v-if="stdSampleInfo.parentStdNo && !(!isEdit || (!!stdSampleInfo.id&& stdSampleInfo.stdMold=='2'))" slot="suffix" type="close-circle" theme="filled" @click="handleEmpty('parentStdNo')" title="清空"/>
                  </a-input>
                </a-form-model-item>
              </a-col>
             
               <a-col :span="8">
                <a-form-model-item   label="现标准样编号" prop="stdNo">
                  <a-input  v-model.trim="stdSampleInfo.stdNo"  disabled placeholder="系统自动生成" allowClear/>
                 
                </a-form-model-item>
              </a-col>
                   
              <a-col :span="8">
                <a-form-model-item label="执行日期"   prop="executeTime">
                    <a-date-picker  :disabled-date="(val)=>disabledDate(val,'executeTime')" :disabled="!isEdit" v-model="stdSampleInfo.executeTime" valueFormat="YYYY-MM-DD" placeholder="请选择执行日期" />
                </a-form-model-item>                
              </a-col>         
            </a-row>
             <a-row :gutter="24">
              <a-col :span="24">
                  <a-form-model-item   label="质检实验室" prop="lab">
                  <a-textarea  :auto-size="{ minRows: 1, maxRows: 5 }" :disabled="!isEdit" v-model="stdSampleInfo.lab" placeholder="请选择质检实验室" @click="selectOpen('lab')" read-only/>
                 
                </a-form-model-item>            
              </a-col>
              
                
                 <!-- <a-col :span="8">
                <a-form-model-item label="自动废止日期"   prop="autoAbolishTime">
                    <a-date-picker  :disabled-date="disabledDate" :disabled="!isEdit" v-model="stdSampleInfo.autoAbolishTime" valueFormat="YYYY-MM-DD" placeholder="请选择自动废止日期" />
                </a-form-model-item>                
              </a-col>  -->
               
             </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
               
                  <a-form-model-item label="制定/更新的原因" prop="reason">
                    <a-textarea :disabled="!isEdit" v-model.trim="stdSampleInfo.reason" allowClear
                                placeholder="请输入制定/更新的原因，500字以内。"
                                :maxLength="500"
                                :auto-size="{ minRows: 2, maxRows: 5 }"/>
                  </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
               
                  <a-form-model-item label="标准样变化说明" prop="changeReason">
                    <a-textarea :disabled="!isEdit" v-model.trim="stdSampleInfo.changeReason" allowClear
                                placeholder="请输入标准样变化说明，500字以内。"
                                :maxLength="500"
                                :auto-size="{ minRows: 2, maxRows: 5 }"/>
                  </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section>                
          <div class="section-header mt15">
            <div>该标准还适用以下物料</div>
            <div class="btn-line">
              <a-button class="hte-btn add-btn" type="primary" :loading="btnLoading" @click="selectOpen('applyMaktx')" v-if="isEdit">新增</a-button>
              <a-button class="hte-btn"  :loading="btnLoading" @click="handAction('delApplyMatnr')" v-if="isEdit">删除</a-button>
            </div>
          </div>
          <div class="section-table">
            <div>
              <a-table
                class="hte-table-content"
                :columns="applyMatnrColumns"
                :data-source="applyMatnrs"
                :pagination="false"
                :rowSelection="{selectedRowKeys: selectedRowKeysApplyMatnr, onChange: onSelectChangeApplyMatnr}"
                rowKey="code"                
                bordered
                size="middle"
              >
            
               
              </a-table>
              <MaraSelect ref="applyMaktx" :isAllSelect="true"  @ok="(res)=>selectOk(res,'applyMaktx')" :clear="false" v-show="false"></MaraSelect>
            </div>
          </div>        
        </section> 
        </a-form-model>
        <section>
          <div class="section-header">
            <span>原标准样内容</span>
           
          </div>
          <div class="section-table">            
            <template>
              <a-table
                class="hte-table-content hte-table-headchild"
                :columns="contentColums"
                :data-source="parentSampleContents"
                :pagination="false"
                :loading="desLoading"
                bordered
                size="middle"
                rowKey="targetCode"
              >
                <template slot="action" slot-scope="text, record">
                </template>
                <template slot="remark" slot-scope="text, record">

                    <span class="text-over" :title="text">{{text}}</span>
                </template>
                <template slot="defectDesc" slot-scope="text, record">
                   
                    
                  <span class="text-over" :title="text">{{text}}</span>
                </template> 
              </a-table>
            </template>
          </div>
          
          
        </section>   
        <section>
          <div class="section-header">
            <span>现标准样内容</span>
           
          </div>
          <div class="section-table">            
            <template>
              <a-table
                class="hte-table-content hte-table-headchild"
                :columns="contentColums"
                :data-source="sampleContents"
                :pagination="false"
                :loading="desLoading"
                bordered
                size="middle"
                rowKey="targetCode"
              >
                <template slot="remark" slot-scope="text, record">
                      <a-textarea style="width: 95%;" v-if="isEdit" v-model="record.remark" allowClear
                                placeholder="请输入备注，500字以内。"
                                :maxLength="500"
                                :auto-size="{ minRows: 2, maxRows: 5 }"/>  
                    
                    <span class="text-over" :title="text" v-else>{{text}}</span>
                </template>
                <template slot="defectDesc" slot-scope="text, record">
                      <a-textarea style="width: 95%;" v-if="isEdit" v-model="record.defectDesc" allowClear
                                placeholder="请输入缺陷说明，35字以内。"
                                :maxLength="35"
                                :auto-size="{ minRows: 2, maxRows: 5 }"/>  
                    
                      <span class="text-over" :title="text" v-else>{{text}}</span>
                </template>   
                  <template slot="score" slot-scope="text, record">
                       <a-input-number placeholder="请填写0-10数值" style="width: 95%;" v-if="isEdit" v-model="record.score" :precision="1"  :min="0" :max="10"  />
                      <span v-else>{{text}}</span>
                  </template>
                  <template slot="grade" slot-scope="text, record">
                       
                      <a-select show-search :filter-option="filterOption"  v-if="isEdit" v-model="record.gradeCode" @change="(val,option)=>gradeChange(val,option,record)" style="width: 95%;"  placeholder="请选择评级" allow-clear>
                        <a-select-option :value="item.codeNo" v-for="(item,i) in record.codes" :name="item.codeName" :key="i + item.codeNo"> {{item.codeName}} </a-select-option>
                      </a-select>
                      <span v-else>{{record.grade}}</span>
                  </template>
              </a-table>
            </template>
          </div>
          
          
        </section>  
        <section >   
        <template>
              <div class="section-header mt15">
                <div>附件上传<span class="em"></span></div>
              </div>
              <div class="section-table">
                 
                <div class="btn-line"  v-show="!!stdSampleInfo.id">
                  <template>
                    <ht-upload
                      v-if="!!stdSampleInfo.id"
                      ref="myUpload"
                      class="upload-demo"
                      style="margin-left:0"
                      multiple
                      dbKey="Trd"
                      busField="stdAttach"
                      busType=""
                      :busKey="!!stdSampleInfo.stdSampleBatchId? stdSampleInfo.stdSampleBatchId: stdSampleInfo.id "
                      ftpKey="ftp"
                      v-model="fileData"
                      :show-file-list="false"
                    >
                      <a-button class="hte-btn add-btn" v-if="isEdit && !!stdSampleInfo.id" type="primary" icon="plus">上传</a-button>
                    </ht-upload>                    
                  </template>
                  <a-button class="hte-btn" @click="handAction('download')">下载</a-button>
                  <a-button class="hte-btn" v-if="isEdit"  @click="handAction('delAttach')" >删除</a-button>
                </div>
                <div>
                 <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                 
                  <a-table
                    class="hte-table-content"
                    :columns="fileColumns"
                    :data-source="fileData"
                    :pagination="false"
                    :loading="btnLoading"
                    rowKey="id"
                    :row-selection="{ selectedRowKeys: selectedAttachRowKeys, onChange: onSelectAttachChange }"
                    bordered
                    size="middle"
                  >
                  <template slot="fileName" slot-scope="text, record">
                  <template>
                    <a @click="showAttach(record)">{{ record.fileName }}</a>
                  </template>
                </template>
                  </a-table>
                </a-tooltip>
                  
                </div>

              </div>
            </template>  
            </section>
        <section v-if="processInstanceId&&processInstanceId!=''">
          <div class="section-header">审批意见</div>
          <div class="section-table">
            <template>
              <ht-approval
                ref="childrenRef"
                :process-instance-id="processInstanceId"
                :options="options"
                :custom="custom"
                @reject="afterReject"
                @back="backAction"
                @submit="afterSubmit"
                :before-reject="beforeReject"
                :show-task-history="true"
                :history-dialog="historyDialog"
                :message-id="messageId"
                :showPrintBtn="showPrintBtn"
                :show-upload-btn="true"
                :attach-preview="(file)=>attachPreview(file)"
                :hidden-task-def-key="hiddenTaskDefKey"
                :before-submit="beforeSubmit"
                :taskLoad="taskLoad"
                :snapshotConfigs="snapshotConfigs">
              </ht-approval>
            </template>
          </div>
        </section>
        </div>
      </div>
    </a-spin>

        <process-user-select  :columns="selUserCols" @selectUserConfirm="selectUserConfirm" ref="processUserSelect" />
        <div class="btn-line btn-bottom-fixed" >
          <a-button class="hte-btn" @click="save()" v-show="isEdit" :loading="btnLoading">保存</a-button>
          <!-- <a-button class="hte-btn add-btn" type="primary" @click="onSubmitForm" v-show="isEdit && !!stdSampleInfo.id&& !currentTaskEdit" :loading="btnLoading">提交审批</a-button> -->
          <!-- <a-button class="hte-btn del-btn" @click="delForm" :loading="btnLoading" v-show="isEdit && !!stdSampleInfo.id">删除</a-button> -->
        </div>

         <table-select-modal  title="选择质检实验室"  :listUrl="url.labList" :params="{}" rowKey="cno" rowName="cnm" :isAllSelect="true" 
        :importColumns="labSelectColums" ref="lab" @ok="(res)=>selectOk(res,'lab')"></table-select-modal>
        <table-select-modal  title="选择标准样编号"  :listUrl="url.list" :params="{maraMatnr:stdSampleInfo.maraMatnr,statusIn:'3,4',scopeFlag:false}" rowKey="id" rowName="stdNo"  keywordKey="stdNoKeyWord" :isAllSelect="false" 
        :importColumns="parentStdNoSelectColums" ref="parentStdNo" @ok="(res)=>selectOk(res,'parentStdNo')"></table-select-modal>

        
  </div>
</template>
<script>
import Vue from 'vue'
import { Modal } from 'ant-design-vue'
import {ACCESS_TOKEN, USER_INFO,USER_NAME} from '@/store/mutation-types'
import '@/config/upload.install.js'
import '@/config/ht-approval.install.js';
import {formatSize, isPreview} from '@/components/hteUpload/common/utils'
import { endWith } from '@/utils/common.js'
import {codeInfoList} from '@/api/codeInfo'
import {getAction,postAction,previewAttach,deleteAction} from '@/api/manage'
import moment from 'moment';
import { stdSampleStatusFilter } from '@/utils/filter'
export default {
  name: 'StdSampleInfo',
  components: {
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
    QuestionnaireAuditPage: () => import('@/components/tools/projectBuild/QuestionnaireAuditPage'),
    TableSelectModal: () => import('@/components/tools/TableSelectModal'),
    MaraSelect: () => import('@/components/tools/MaraSelect'),
    FixedMenu: () => import('@/components/tools/FixedMenu'),
  },

  data() {
    return {
      maraSelectColums:[
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'matnr'
          },
           {
            title:'物料名称',
            align:"center",
            dataIndex: 'maktx'
          }
        ],
        labSelectColums:[
          {
            title:'编码',
            align:"center",
            dataIndex: 'cno',
            width:50,
          },
           {
            title:'实验室全称',
            align:"center",
            dataIndex: 'cname',
            width:300,
          },
          {
            title:'实验室简称',
            align:"center",
            dataIndex: 'cnm'
          }
        ],
        parentStdNoSelectColums:[
           {
            title:'标准样编号',
            align:"center",
            dataIndex: 'stdNo',
            width:200,
          },
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'maraMatnr',
            width:120,
          },
           {
            title:'物料名称',
            align:"center",
            dataIndex: 'maraMaktx'
          }
        ],
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'StdSampleInfo',
      },
      currUser: Vue.ls.get(USER_INFO).username,
      btnShow:false,
      btnLoading:false,
      desLoading:false,
      url:{
        queryBaseById:'/stdSample/queryBaseById',
        saveStdSample:'/stdSample/saveStdSample',
        getTree:"/stdSampleType/getTree",
        downLoadBatch:'/common/downLoadBatchWithFileName', // 下载
        delete:'/stdSample/delete',
        submitStdSample:'/stdSample/submitStdSample',
        queryBaseByNo:'/stdSample/queryBaseByNo',
        sapMaraList:'/sapMara/list',
        list:'/stdSample/list',
        labList:'/stdLab/list',
        queryContentQms:'/stdSample/queryContentQms'
      },      
      sampleBaseId:this.$route.query.sampleBaseId,
      stdSampleInfo: {
       
        sampleContents:[],
        parentSampleContents:[],
      },
      rules: {              
        maraMatnr: [{required: true, message: '请选择物料名称', trigger: 'change'}],
        maraMaktx: [{required: true, message: '请选择物料编号', trigger: 'change'}],
        stdType: [{required: true, message: '请选择目录分类', }],
        stdMold: [{required: true, message: '请选择标准样类型', }],
        stdNo: [{required: true,message: '请输入现标准样编号',trigger: 'blur' ,whitespace: true},],
        executeTime: [{required: true, message: '请选择执行日期', trigger: 'change'}],
        autoAbolishTime: [{required: true, message: '请选择废止日期', trigger: 'change'}],
        lab: [{required: true, message: '请选择质检实验室', trigger: 'change'}],
        reason: [{required: true,message: '请输入制定/更新的原因',trigger: 'blur' ,whitespace: true},],        
        
      },
         
      // 流程引擎
      processInstanceId:'',
      hiddenTaskDefKey:"submit",
      options: {
        request: {
          baseUrl: this.API_BASE_URL,   // 业务系统根路径
          timeOut: 30000,  // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token']=Vue.ls.get(ACCESS_TOKEN)
            return config
          }
        },
        userId: Vue.ls.get(USER_NAME)
      },
      returnShowConfirm: false,   // 退回显示确认框
      messageId: '',          // 工作台URL里面的msgId参数
      showPrintBtn: false,
      custom: {},
      historyDialog: {}, // 审批历史模态框属性
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper'
        }
      ],
      // 审批人
      selUserCols:[
        // { label: '产品分厂主管', field: 'supervisorUser', username: '', realname: '', required: true,limit:1 },
        // { label: '工艺部主管', field: 'processDepartmentUser', username: '', realname: '', required: true,limit:1 },
        // { label: '质检所/质检部', field: 'qualityDepartmentUser', username: '', realname: '', required: true,limit:1 },
        // { label: '产品研究院分主管', field: 'productDepartmentUser', username: '', realname: '', required: true,limit:1 },
        { label: '相关分厂工艺质检', field: 'supervisorUser', username: '', realname: '', required: true },
        { label: '质检部主管', field: 'qualityMainDepartmentUser', username: '', realname: '', required: true,limit:1 },
        { label: '产品研究院主管', field: 'productMainDepartmentUser', username: '', realname: '', required: true,limit:1 },
      ],
     
      // 标准样内容
      contentColums: [
       {
          title: '指标',
          dataIndex: 'target',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'target' },
        },
        {
          title: '指标编码',
          dataIndex: 'qmsTargetCode',
          width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'qmsTargetCode' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '25%',
          align: 'center',
           scopedSlots: { customRender: 'remark' },
        },
      
         {
          title: '评级',
          dataIndex: 'grade',
          width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'grade' },
        },        
        {
          title: '评分',
          dataIndex: 'score',
           width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'score' },
        },
        {
          title: '缺陷说明',
          dataIndex: 'defectDesc',
           width: '15%',
          align: 'center',
           scopedSlots: { customRender: 'defectDesc' },
        },
      ],
      sampleContents:[],
      parentSampleContents:[],
      // 字典
      dict: {
        orderList0: [], // 准样内容指标
        orderList1: [], // 项目奖励项目类别
      },
      treeData:[],
      spinning:false,
      contentQms: [],
      maraCustomParam:{status:0,maraLikeRightIn:'6,7,8',maraLikeRight:'6'},
      applyMatnrColumns: [
      {
          title: '物料名称',
          dataIndex: 'name',
          width: '50%',
          align: 'center',
          scopedSlots: { customRender: 'applyMaktx' },
        },
       {
          title: '物料编号',
          dataIndex: 'code',
          width: '50%',
          align: 'center',
        },
      ],
      selectedRowKeysApplyMatnr:[],
      applyMatnrs:[],
      currentTaskEdit:false,
      fileColumns: [
        {title: '附件名称',dataIndex: 'fileName',scopedSlots: { customRender: 'fileName' }},
        {title: '文件大小',dataIndex: 'size',width: 150,align: 'center',customRender:function (text) {return formatSize(text)}},
        {title: '上传人',dataIndex: 'uploaderName',width: 150,align: 'center',},
        {title: '上传时间',dataIndex: 'uploadTime',width: 230,align: 'center',},        
      ],
      fileData: [],
      selectedAttachRowKeys:[],
    }
  },
   filters: {
    stdSampleStatusFilter,
  },
  created(){
    this.initSelectData(); // 查询字典
    this.getTree()
    this.getStdSampleInfo()
  },
   watch:{
    currentTaskEdit:function (val) {
      if(val){
        this.getStdSampleInfo()
      }

    },
    },
    computed:{
    isEdit(){
      return !this.sampleBaseId || (this.stdSampleInfo.status==1 && this.stdSampleInfo.createUserId==this.currUser)
       || (this.stdSampleInfo.status==2 && this.currentTaskEdit)
    },
    
  
  },
 
  methods: {
    /**
     * 初始查询 
     */
   getStdSampleInfo(){
    this.sampleContents = []  
    let sampleContents = []
     
    if(!this.sampleBaseId){
        let stdSampleInfo = {status:1, sampleContents:sampleContents,parentSampleContents:[]}
        stdSampleInfo.editDep=this.userinfo.info.deptName;
        stdSampleInfo.editDepId=this.userinfo.info.deptId;
        stdSampleInfo.createUser=this.userinfo.info.realname;
        stdSampleInfo.createUserId=this.currUser;
        stdSampleInfo.dataVersion = 1;
        this.sampleContents = sampleContents
        this.stdSampleInfo = stdSampleInfo
        return
    }
     this.btnLoading=true;
    getAction(this.url.queryBaseById,{sampleBaseId:this.sampleBaseId}).then( res=>{
          if(res.code== 200){
             this.stdSampleInfo =  res.result || {sampleContents:[],parentSampleContents:[]}
             this.sampleContents = this.stdSampleInfo.sampleContents
             
             if(this.stdSampleInfo.status == 1 || this.currentTaskEdit){
               this.queryContentQms()

                
             }
             this.parentSampleContents = this.stdSampleInfo.parentSampleContents || []
             this.processInstanceId = this.stdSampleInfo.processInstanceId
             this.applyMatnrs = this.stdSampleInfo.applyMatnrs || []
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{
           this.btnLoading=false;
        })
   },
   getTree(){
        getAction(this.url.getTree,{disableFlag:true}).then(res=>{
          if(res.code== 200){
             this.treeData =  res.result
          }else{
            this.$message.warning(res.message)
          }
        })

      },
    initSelectData() {
      const list = ['标准样类型']
      list.forEach((item, index)=>{
        codeInfoList({type:item, pageSize:-1,isdel: 0, column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict['orderList'+ index] = res.result.records   
             if(index == 0){
             }        
          } else {
            this.$message.warning('查询字典异常:' + res.message)
          }
        })
      })      
    },
     queryContentQms(){
    this.contentQms  = []
    this.sampleContents = []  
    // if(!this.stdSampleInfo.labCode) {
    //   return
    // }
   let ciniSmp = this.stdSampleInfo.labCode.split(',')[0]

   postAction(this.url.queryContentQms,{}).then(res=>{
      if (res.code == 200) {
        let content = res.result  || {vtCodes:[]}
          let contentQms = content.vtCodes.map(item=>{
          let codesSnapshot = item.codes || []
          codesSnapshot = JSON.stringify(codesSnapshot)
          return {target:item.vtdesc ,targetCode:item.verwmerkm,qmsTargetCode:item.verwmerkm,codes:item.codes,codesSnapshot: codesSnapshot,selectSet:item.selectSet}
        })
        this.contentQms = contentQms
        let contentArr = []
        contentQms.forEach(item=>{
            let content = this.stdSampleInfo.sampleContents.find(content=>{return content.targetCode == item.targetCode})
            if(!!content){
                content.qmsTargetCode = item.qmsTargetCode
                content.target = item.target
                content.codes = item.codes
                content.codesSnapshot = item.codesSnapshot
                content.selectSet= item.selectSet
                contentArr.push(content)
            }else{
                contentArr.push(item)    
            }
          })
          this.sampleContents = contentArr
      } else {
        this.$message.warning('查询标准样内容异常:' + res.message)
      }

   })
      
     
    },
    /**
     * 保存
     */
    save(type){
      const vm=this;

      if(!this.stdSampleInfo.stdMold){
        this.$message.warning("请选择标准样类型");
        return;
      }
      let content = `标准样类型【制定】、物料名称、目录一旦确定将不可更改，是否确定正确？`
      if(this.stdSampleInfo.stdMold=='2'){
        if(!this.stdSampleInfo.parentStdNo){
          this.$message.warning("请选择原标准样编号");
          return;
        }
        content = `标准样类型【改版】、物料名称、目录、原标准样编一旦确定将不可更改，是否确定正确？`
      }
      if(!this.stdSampleInfo.stdType){
        this.$message.warning("请选择目录分类");
        return;
      }
      if(!this.stdSampleInfo.maraMatnr){
        this.$message.warning("请选择物料名称");
        return;
      }
      if(!this.stdSampleInfo.id){
        Modal.confirm({
          title: "提示",
          content: content,
          onOk: function() {
            vm.doSave(type)
          },
          onCancel() {},
        });
      }else if(this.currentTaskEdit){
         vm.onSubmitForm() 
      } else{
         vm.doSave(type)

      }
    
      
    },
    getSaveParams(){
      this.sampleContents.forEach(item=>{

        item.score = !!item.score?item.score:0
        item.gradeCode = !!item.gradeCode?item.gradeCode:''
      })
      this.stdSampleInfo.sampleContents =  this.sampleContents
      this.stdSampleInfo.parentSampleContents =  this.parentSampleContents
      this.stdSampleInfo.applyMatnr =!this.applyMatnrs?'': this.applyMatnrs.map(i=>{return i.code}).join(',')
      return this.stdSampleInfo
    },
    queryBaseByNo(){
        this.parentSampleContents = []
         getAction(this.url.queryBaseByNo,{stdNo:!this.stdSampleInfo.parentStdNo?'':this.stdSampleInfo.parentStdNo}).then(res=>{
          if(res.code== 200){
             let result = res.result || {sampleContents:[]}
             this.parentSampleContents = result.sampleContents || []
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{

        })
    },
    doSave(type){
      this.btnLoading=true;
      
      postAction(this.url.saveStdSample,this.getSaveParams()).then(res=>{
        if(res.success){
          let result = res.result
          if(!this.stdSampleInfo.id){
             this.$router.push({ path: '/blank', query: {reload : '1', backUrl: encodeURI(`/stdSample/info?sampleBaseId=${result.id}`)} })  
          }else{
            this.getStdSampleInfo();
           
            this.$message.success("保存成功")
          }
          
        }else{
          this.$message.warning(res.message)
        }
      }).catch(res=>{
        this.$message.warning(res.message)
      }).finally(res=>{
        this.btnLoading=false;

      })
    },
   
    handleEmpty(type){
      if(!this.isEdit){return}
      if(type == 'parentStdNo'){
        this.$set(this.stdSampleInfo,'parentStdNo','')
        this.parentSampleContents = [] 
      }
    },
    setStdType(){

      // if(!!this.stdSampleInfo.stdType){return}
      getAction(this.url.list,{maraMatnr:this.stdSampleInfo.maraMatnr,currentDataVersion:1,scopeFlag:false,pageSize:1,column:'t.push_time',order:'Desc'}).then(res=>{
          if(res.code== 200){
             let records = res.result.records || []
             if(records && records.length > 0){
             this.$set(this.stdSampleInfo,'stdType',records[0].stdType)
             }else{
              this.$set(this.stdSampleInfo,'stdType',null)
             }
          }else{
            this.$message.warning(res.message)
          }
        }).finally(res=>{

        })
    },
 
    /**
     * 提交审批 
     */
    onSubmitForm() {
      let vm=this;
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let stdSampleInfo = this.getSaveParams()
          if(!stdSampleInfo.sampleContents || stdSampleInfo.sampleContents.length == 0){
              this.$message.warning(`现标准样内容为空`)
              return
          }
          for (let index = 0; index < stdSampleInfo.sampleContents.length; index++) {
            const element = stdSampleInfo.sampleContents[index];
            if(!element.remark){
              this.$message.warning(`指标【${element.target}】请填写备注`)
              return
            }
            if(!element.grade){
              this.$message.warning(`指标【${element.target}】请选择评级`)
              return
            }
              if(!element.score && element.score != 0){
              this.$message.warning(`指标【${element.target}】请填写分数`)
              return
            }
            
          }
          if(!!stdSampleInfo.parentStdNo && stdSampleInfo.parentStdNo ==  stdSampleInfo.stdNo) {
            this.$message.warning(`原标准样编号【${stdSampleInfo.parentStdNo}】与现标准样编号不允许一致`)
              return
          } 
          const index = this.applyMatnrs.findIndex(v =>v.code.trim() === stdSampleInfo.maraMatnr.trim());
          if(index!=-1){
            this.$message.warning(`适用物料第${index + 1}行【${stdSampleInfo.maraMatnr}】与物料编号不允许一致`)
              return
          }
          if(vm.currentTaskEdit){
            //申请发布节点保存
            vm.doSave()
          }else{
          vm.$refs.processUserSelect.doSelect();

          }
        } else {
          return false;
        }
      });
    },
    delForm(){
    const that = this
      Modal.confirm({
          title: `请确认是否删除?`,          
          onOk: function() {
           deleteAction(that.url.delete, {id:that.stdSampleInfo.id})
            .then((res) => {
              if (res.code == 200) {
                that.$message.success('删除失败成功')
                window.CloseCefTab ? window.CloseCefTab():window.close()
              } else {
                that.$message.warning('删除失败:' + res.message)
              }
            })
            .catch((res) => {
              that.$message.warning('删除失败:' + res.message)
            })
          }
        });
      
    },
   
    selectUserConfirm(cols){
      if(!cols||cols.length===0){
        this.$message.warning('没有选择审批人');
        return;
      }
      let data = {};
      cols.forEach((item) => {
        data[item.field] = item.username
      });
      let stdSampleInfo = this.getSaveParams()
      stdSampleInfo.approvalPerson = data;
      this.spinning = true
      this.btnLoading = true
      //参数组装完毕，发起流程
      postAction(this.url.submitStdSample, stdSampleInfo)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('发起审批流程成功')
            this.getStdSampleInfo();
          } else {
            this.$message.warning('发起流程失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('发起流程异常:' + res.message)
        }).finally(()=>{
          this.spinning = false
          this.btnLoading = false
        })
    }, 

    //-------------流程回调------start
    beforeReject (res) {
      // 驳回前置动作
      return this.checkOptionValue();
    },
    afterReject (res) {
      // 用户点击驳回后成功返回后的处理
      this.getStdSampleInfo();
    },
    backAction (res) {
      this.getStdSampleInfo();
    },
    beforeSubmit(){
      this.currentTaskEdit = false
      this.spinning = true
      return true
    },
    afterSubmit (res) {
          // 用户点击提交后成功返回后的处理
      this.spinning = false
      this.getStdSampleInfo();
    },
    taskLoad(task){
      if(task.taskDefKey === 'submitPublish') {
        this.currentTaskEdit = this.currUser == this.stdSampleInfo.submitUserId
           
      }
    },
    checkOptionValue() {
      let options = this.$refs.childrenRef.data;
      if (options == '' || options == null || options == undefined) {
        this.$message.warning("审批意见不能为空", 3000);
        return false;
      } else {
        return true;
      }
    },
    attachPreview(file,dbKey='Trd') {
      if(dbKey == 'Sac' && this.stdSampleInfo.allAuditors.indexOf(this.currUser)<0&&this.stdSampleInfo.createUserId!==this.currUser){
        this.$message.warning("只有审批人和奖励申请单创建人才可查看附件", 3000);
        return;
      }

      let params={
        id:file.id,
        dbKey:dbKey
      };
      previewAttach(params,'/common/previewAttachProcess').then(result=>{
        const url=URL.createObjectURL(result)
        window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    //-------------流程回调------end
  
   
    handleChange(type){
    },
    
      handAction(type,record,index){      
      let that = this
      
      if(type == 'download'){
        // 下载
        if(this.selectedAttachRowKeys.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        let attachIds=this.selectedAttachRowKeys.join(",");
        this.doDownLoadBatch(attachIds);
      }
     
      if(type == 'delAttach'){
        // 删除        
        if(this.selectedAttachRowKeys.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        const that = this;
     
        Modal.confirm({
          title: '请确认是否删除此附件?',          
          onOk: function() {
            for (let i = that.selectedAttachRowKeys.length - 1; i > -1; i--) {
              const id = that.selectedAttachRowKeys[i] ;
              const obj = {id,dbKey:'Trd',ftpKey:'ftp'}
              that.$refs['myUpload'].delete(obj);
            }  
            that.selectedAttachRowKeys = []
          }
        });
      }
      if(type =='his'){
          this.gotoDetail(`/stdSample/hisList/${this.stdSampleInfo.stdSampleId}/${this.stdSampleInfo.id}`)
      }
      
      if(type =='delApplyMatnr'){
        // 插入
        if (this.selectedRowKeysApplyMatnr.length == 0) {
            this.$message.warning('请选择至少一条数据！')
            return
          }
          Modal.confirm({
            title: '确认删除',
            content: '请确认是否删除适用配料?',
            onOk: function () {
              that.selectedRowKeysApplyMatnr.forEach(code => {
                const index = that.applyMatnrs.findIndex(v => v.code.trim() === code.trim() );
                if(index != -1){
                  that.applyMatnrs.splice(index, 1);  
                }              
              });
              that.selectedRowKeysApplyMatnr = [];
            },
          })

      }
      
      
    },
     gotoDetail(url) {
      let routeUrl = this.$router.resolve({
        path: url,
      })
      window.open(routeUrl.href, '_blank')
    },
     doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(this.stdSampleInfo.stdNo+'附件.zip');
    },
    selectOpen(ref){
      if(!this.isEdit){return}
     if(ref == 'parentStdNo' && !this.stdSampleInfo.maraMatnr){
      this.$message.warning('请选择物料名称');
      return
     }
      this.$refs[ref].open();
    },
    selectOk(res,ref){
      debugger
      let data = [...res]
      
      if(ref == 'mara'){
        this.$set(this.stdSampleInfo,'maraMatnr',data[0].matnr)
        this.$set(this.stdSampleInfo,'maraMaktx',data[0].maktx)
        this.$set(this.stdSampleInfo,'stdType',null)
        this.$set(this.stdSampleInfo,'parentStdNo','')
        this.parentSampleContents = []
        //自动选择目录
        this.setStdType()
      }
      if(ref == 'lab'){
        let labCode = data.map(item=>{return item.cno})
        let lab = data.map(item=>{return item.cnm})
        this.$set(this.stdSampleInfo,'labCode',labCode.join(','))
        this.$set(this.stdSampleInfo,'lab',lab.join(','))
        this.queryContentQms()
      }
      if(ref == 'parentStdNo'){
        this.$set(this.stdSampleInfo,'parentStdNo',data[0].stdNo)
        //带出原标准样内容
        this.queryBaseByNo(data[0].stdNo)
      }
      if(ref == 'applyMaktx'){
        this.selectedRowKeysApplyMatnr = []
       
        data.forEach(item=>{
          const index = this.applyMatnrs.findIndex(v =>v.code.trim() === item.matnr.trim());
          if(index == -1 && item.matnr.trim() != this.stdSampleInfo.maraMatnr.trim()){
            this.applyMatnrs.push({code: item.matnr,name :item.maktx})

          } 
        })
      }
      this.$refs[ref].close()

    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    gradeChange(val,option,record){
      let name = !!option.data.attrs ?  option.data.attrs.name:''
      record.grade = name
    },
    disabledDate(current,type) {
      // Can not select days before today and today
      if(type == 'executeTime'){
        return current && current < moment().subtract(1, 'days');
      }
       return current && current < moment().add(7, 'days');
    },
    dayDif(futurnDate,currentDate = new Date()){
      return  (futurnDate.getTime - currentDate.getTime ) / (1000 * 60 * 60 *24)
    },
    maraChange(e){
      this.maraCustomParam = Object.assign(this.maraCustomParam,{maraLikeRight:e.target.value}) 
      this.$refs.mara.loadData()
    },
    onSelectChangeApplyMatnr(selectedRowKeys, selectionRows) {
     
        this.selectedRowKeysApplyMatnr = selectedRowKeys;
    },
    stdMoldChange(e){
      delete this.rules.parentStdNo
      let required = false
      if(this.stdSampleInfo.stdMold == '2'){
        required = true
      }
      this.$set(this.rules,'parentStdNo',[{required: required,message: '请选择原标准编号',trigger: 'change' ,whitespace: true},])
    },
    onSelectAttachChange(selectedRowKeys, selectionRows) {
      this.selectedAttachRowKeys = selectedRowKeys
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(`标准样${this.stdSampleInfo.stdNo}附件.zip`);
    },
    showAttach(record) {
      var id = record.id
      var fileName = record.fileName
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.$emit('afterDown', [record])
        this.doDownLoadBatch(id)
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
  }  
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import '~@views/library/hteFile.less';
em{margin-left: 5px;}
.mt20{margin-top:20px;}
.btn-span{margin-right: 15px;
  &:last-of-type{margin-right: 0;}
}
/deep/ .mes-box{
  select{width: 200px;margin-left: 10px;}
}
/deep/ .upload-demo{display: inline-block;margin-left: 15px;}
/deep/ #process-container {
  width: unset !important;
}
/deep/ #process-container .process-item .info-fullMessage {
  max-width: 1200px;
}

.text-over{color: #646566;overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;      
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
      overflow-wrap: break-word;
      /* min-height: 50px; */
    }
.floatNavLeft {
  position: fixed;
  top: 180px;
  left: 30px;
  z-index: 1;

  > button {
    display: block;
    margin-bottom: 10px;
  }
}

@media (max-width: 1080px) {


  .floatNavLeft {
    left: 5px;

    > button {
      padding: 0 2px;
      font-size: 12px;
    }
  }
}
</style>
